package com.cjt.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

public class ImageUtil {
    /**
     * 转换为base64格式
     *
     * @param image
     * @return
     */
    public static String encode2Base64Jpg(BufferedImage image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// io流
        try {
            ImageIO.write(image, "jpg", baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();// 转换成字节
        Base64.Encoder encoder = Base64.getEncoder();
        String jpgBase64 = encoder.encodeToString(bytes).trim();// 转换成base64串
        jpgBase64 = jpgBase64.replaceAll("\n", "").replaceAll("\r", "");// 删除 \r\n

        return "data:image/jpeg;base64," + jpgBase64;
    }
}
